﻿using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

namespace DL.Characters.Camera.CameraShake
{
    public class CameraShake : MonoBehaviour
    {
        protected UnityEngine.Camera MainCamera;
        [SerializeField]
        protected AnimationCurve ShakeCurve;
        
        [SerializeField]
        protected bool isShaking;

        private Vector3 m_OriginalPosition;
        
        private void Start()
        {
            // MainCamera = GetComponentInChildren<UnityEngine.Camera>();
            // m_OriginalPosition = this.MainCamera.transform.position;
            m_OriginalPosition = transform.position;
        }

        private void Update()
        {
            if (Keyboard.current.kKey.isPressed)
            {
                Debug.Log("震屏开始");
                Shake(0.25f, 0.01f);
            }
        }

        public void Shake(float duration = 0.25f, float amplitude = 1f)
        {
            StartCoroutine(ShakeCoroutine(duration, amplitude));
        }

        private IEnumerator ShakeCoroutine(float duration, float amplitude)
        {
            isShaking = true;
            float elapsedTime = 0f;
            while (elapsedTime < duration)
            {
                float d = ShakeCurve.Evaluate(elapsedTime / duration);
                Vector3 b = Random.insideUnitSphere * amplitude * d;
                // MainCamera.transform.position = m_OriginalPosition + b;
                transform.position = m_OriginalPosition + b;
                elapsedTime += Time.deltaTime;
                yield return null;
            }
            transform.position = m_OriginalPosition;
            // MainCamera.transform.position = m_OriginalPosition;
            isShaking = false;
        }
    }
}